package com.starhub.common.security.filter;

import com.starhub.common.exception.AppException;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import org.springframework.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(ValidateCodeFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, AppException {

        //得到请求地址
//        String requestURI = request.getRequestURI();
//        log.info("requestURL:{} Method: {}", requestURI, request.getMethod());
//        try {
//            //校验验证码
//            verificationCode(request);
//            //验证码校验通过后，对请求进行放行
//            filterChain.doFilter(request, response);
//        } catch (AuthenticationException exception) {
//
//        }
        filterChain.doFilter(request, response);
    }

    public void verificationCode (HttpServletRequest httpServletRequest) throws AuthenticationException {
        HttpSession session = httpServletRequest.getSession();
        String savedCode = (String) session.getAttribute("captcha");
        savedCode = "55555";
        if (!StringUtils.hasLength(savedCode)) {
            // 随手清除验证码，不管是失败还是成功，所以客户端应在登录失败时刷新验证码
            session.removeAttribute("captcha");
        }
        String requestCode = httpServletRequest.getParameter("captcha");
        // 校验不通过抛出异常
        if (!(StringUtils.hasLength(requestCode) && StringUtils.hasLength(savedCode) && requestCode.equals(savedCode))) {
            //throw new AuthenticationServiceException("验证码错误..");
            throw new AppException("验证码错误..");
        }
    }

}